import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import prisma from '@/lib/prisma';
import fs from 'fs/promises';
import path from 'path';

//删除上传的内容
export async function DELETE(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  const session = await getServerSession(authOptions);
  if (!session?.user?.id) {
    return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
  }

  const { id: resourceId } = params;

  if (!resourceId) {
    return NextResponse.json({ error: 'Resource ID is required' }, { status: 400 });
  }

  try {
    const resource = await prisma.resource.findUnique({
      where: { id: resourceId },
      select: { 
        url: true, 
        experiment: { select: { createdById: true } }
      },
    });

    if (!resource) {
      return NextResponse.json({ error: 'Resource not found' }, { status: 404 });
    }

    const isAdmin = session.user.role === 'ADMIN';
    const isExperimentCreator = resource.experiment.createdById === session.user.id;

    if (!isAdmin && !isExperimentCreator) {
      return NextResponse.json({ error: 'Forbidden: You do not have permission to delete this resource.' }, { status: 403 });
    }

    await prisma.resource.delete({
      where: { id: resourceId },
    });

    if (resource.url && resource.url.startsWith('/uploads/')) {
      const filePathToDelete = path.join(process.cwd(), 'public', resource.url);
      try {
        await fs.unlink(filePathToDelete);
        console.log(`Successfully deleted file: ${filePathToDelete}`);
      } catch (fileError: any) {
        console.warn(`Failed to delete file ${filePathToDelete}: ${fileError.message}`);
      }
    }

    return NextResponse.json({ message: 'Resource deleted successfully' }, { status: 200 });

  } catch (error) {
    console.error(`Error deleting resource ${resourceId}:`, error);
    return NextResponse.json({ error: 'Internal server error while deleting resource' }, { status: 500 });
  }
}
